package lzzy.edu.cn.demothymeleaf.service;

import lzzy.edu.cn.demothymeleaf.controller.ResourceNotFoundException;
import lzzy.edu.cn.demothymeleaf.entity.Article;
import lzzy.edu.cn.demothymeleaf.repository.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ArticleService {
    @Autowired
    private ArticleRepository articleRepository;

    //    @Cacheable(cacheNames = "article")
    public Article findById(Integer id) {
//        if(articleRepository.findById(id).isPresent())
        return articleRepository.findById(id).get();
//        return null;
    }

    public List<Article> findAll() {
        return articleRepository.findAll();
    }

    public Article addArticle(String title, String content) {
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        return articleRepository.save(article);
    }

    //    @CachePut(cacheNames = "article",key = "#article.id")
//    public Article updateArticle(Article article) {
    public Article updateArticle(Integer id,String title,String content)  {
        Article article = new Article();
        article.setId(id);
        article.setTitle(title);
        article.setContent(content);
        return articleRepository.save(article);
    }

    public void deleteArticleById(Integer id) {
        if (articleRepository.existsById(id))
            articleRepository.deleteById(id);
    }

    public Page<Article> findAllByPage(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return articleRepository.findAll(pageable);
    }


    public Article findById(int id) {
        return articleRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Article not found"));
    }

    public void save(Article article) {
        articleRepository.save(article);
    }
}
